package com.chaowei.lims.fragment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import org.ksoap2.serialization.SoapObject;

import com.chaowei.lims.activity.LoginActivity;
import com.chaowei.lims.activity.LoginActivity.AsyncSOBListener;
import com.chaowei.lims.activity.MdfPwdActivity;
import com.chaowei.lims.entity.WcfWrapper;
import com.chaowei.lims.utils.AsyncOptUIListener;

import com.chaowei.lims.utils.CcCircleImageView;

import com.chaowei.lims.utils.InitData;

import com.chaowei.lims.utils.MyApplication;
import com.chaowei.lims.utils.SoapRequest;
import com.chaowei.lims.utils.myDialog;
import com.chaowei.lims.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;

import android.widget.PopupWindow;

import android.widget.LinearLayout;

import android.widget.TextView;
import android.widget.PopupWindow.OnDismissListener;

public class AccountFragment extends Fragment {
	private TextView tv_phone, tvName, tvQQ, tvEmail, tvStatus;
	private LinearLayout LinMdfPwd,linBtnGoOut;
	SharedPreferences sp;
	private String mPhone;
	private boolean isLogin = true;
	private myDialog dialog;
	private String username, realname, qq, Email, status, login_id;
	private TextView tvTitle;
	private ImageView img_back, changePass;
	private MyApplication myApplication;
	private CcCircleImageView img_head;

	public static final int PHOTO_REQUEST_GALLERY = 1;//相册
	public static final int PHOTO_REQUEST_TAKEPHOTO = 2;// 拍照
	SharedPreferences image;//获取存的图片
	private PopupWindow popchoose;
	private View contentView;
	private Button  btn_picture, btn_photo, btn_cancle;
	private Bitmap head;// 头像Bitmap
	@SuppressLint("SdCardPath")
	private static String path = "/sdcard/myHead/";// sd路径
	private SoapObject Sob;



	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_account, container,
				false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		tvTitle = (TextView) getActivity()
				.findViewById(R.id.tv_comtitle_title);
		myApplication = MyApplication.getInstance();
		img_back = (ImageView) getActivity().findViewById(
				R.id.img_comtitle_back);
		tvTitle.setText("个 人 中 心");
		img_back.setVisibility(View.GONE);
		linBtnGoOut = (LinearLayout) getActivity().findViewById(R.id.lin_btnGoOut);
		tv_phone = (TextView) getActivity().findViewById(R.id.tvPhone);
		tvName = (TextView) getActivity().findViewById(R.id.tvName);
		tvQQ = (TextView) getActivity().findViewById(R.id.tvQQ);
		tvEmail = (TextView) getActivity().findViewById(R.id.tvEmail);
		tvStatus = (TextView) getActivity().findViewById(R.id.tvStatus);
		changePass = (ImageView) getActivity().findViewById(R.id.IvchangePass);
		LinMdfPwd = (LinearLayout)getActivity().findViewById(R.id.lin_account_modifypwd);
		username = getActivity().getIntent().getStringExtra("username");
		realname = getActivity().getIntent().getStringExtra("realName");
		qq = getActivity().getIntent().getStringExtra("QQ");
		Email = getActivity().getIntent().getStringExtra("Email");
		status = getActivity().getIntent().getStringExtra("status");
		login_id = getActivity().getIntent().getStringExtra("login_id");
		tv_phone.setText(username);
		tvName.setText(realname);
		tvQQ.setText(qq);
		tvEmail.setText(Email);
		tvStatus.setText(status);
		contentView = LayoutInflater.from(getActivity()).inflate(
				R.layout.popupwindow_accountfragment_choose, null);
		popchoose = new PopupWindow(contentView,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		
		btn_picture=(Button) contentView.findViewById(R.id.btn_picture);
		btn_photo=(Button) contentView.findViewById(R.id.btn_photo);
		btn_cancle=(Button) contentView.findViewById(R.id.btn_cancle);

		// 变更头像
		img_head = (CcCircleImageView) getActivity()
				.findViewById(R.id.img_head);
		img_head.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View v) {
		// TODO Auto-generated method stub
			initChoosePopuWindow(v);
			}
		});


		// 读取头像的图片
		image = getActivity().getSharedPreferences("ImageInfo",
				Context.MODE_PRIVATE);
		
		String imaePath = image.getString(username, null);

		if (image != null && imaePath != null) {
			
			FileInputStream fis;
			try {
				fis = new FileInputStream(imaePath);
				Bitmap bitmap=BitmapFactory.decodeStream(fis);
				img_head.setImageBitmap(bitmap);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
					
			
		}
  
		LinMdfPwd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),MdfPwdActivity.class);
				startActivity(intent);
			}
		});
		linBtnGoOut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog = new myDialog(getActivity());
				dialog.setmTitle("提示");
				dialog.setmMessage("你确定要退出吗？");
				dialog.setNoOnclickListener("取消",
						new myDialog.onNoOnclickListener() {

							@Override
							public void onNoClick() {
								dialog.dismiss();
							}
						});

				dialog.setYesOnclickListener("确定",
						new myDialog.onYesOnclickListener() {

							@Override
							public void onYesClick() {
								dialog.dismiss();
								getActivity().finish();
								Intent itent = new Intent(getActivity(), LoginActivity.class);
								getActivity().startActivity(itent);
							}
						});
				dialog.show();
			}
		});
		/**
		 * 修改密码点击事件
		 */
		changePass.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), MdfPwdActivity.class);
                startActivity(intent);
			}
		});
	}

	/**
	 * 获取系统相册
	 * 
	 * @author Administrator
	 * 
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
      
		switch (requestCode) {
		case 1:
			 if (requestCode == PHOTO_REQUEST_GALLERY && resultCode == Activity.RESULT_OK && data != null) {
				 Uri selectedImage = data.getData();
		            String[] filePathColumns = {MediaStore.Images.Media.DATA};
		            Cursor c = getActivity().getContentResolver().query(selectedImage, filePathColumns, null, null, null);
		            c.moveToFirst();
		            int columnIndex = c.getColumnIndex(filePathColumns[0]);
		            String imagePath = c.getString(columnIndex);
		            cropPhoto(selectedImage);
		            //showImage(imagePath);
		            c.close();
		            //content://media/external/images/media/450646
		            Log.d("测试",imagePath);
			}

			break;
		case 2:
			 if (requestCode == PHOTO_REQUEST_TAKEPHOTO && resultCode == Activity.RESULT_OK) {
				 File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
					cropPhoto(Uri.fromFile(temp));// 裁剪图片
			 }

			break;
		case 3:
			if (data != null) {
				Bundle extras = data.getExtras();
				head = extras.getParcelable("data");
				if (head != null) {
					
					setPicToView(head);// 保存在SD卡中
					img_head.setImageBitmap(head);// 用ImageView显示出来
				}
			}
			break;
		default:
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
    }

	
    
    private void initChoosePopuWindow(View parent) {

		ColorDrawable cd = new ColorDrawable(0x000000);
		popchoose.setBackgroundDrawable(cd);
		// 产生背景变暗效果
		WindowManager.LayoutParams lp = getActivity().getWindow()
				.getAttributes();
		lp.alpha = 0.4f;
		getActivity().getWindow().setAttributes(lp);

		popchoose.setOutsideTouchable(true);
		popchoose.setFocusable(true);
		popchoose.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
		popchoose.showAtLocation((View) parent.getParent(), Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);

		popchoose.update();
		popchoose.setOnDismissListener(new OnDismissListener() {

			// 在dismiss中恢复透明度
			public void onDismiss() {
				WindowManager.LayoutParams lp = getActivity().getWindow()
						.getAttributes();
				lp.alpha = 1f;
				getActivity().getWindow().setAttributes(lp);
			}
		});
		
		

		btn_picture.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent1 = new Intent(Intent.ACTION_PICK, null);
				intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				startActivityForResult(intent1, 1);
				popchoose.dismiss();
			}
		});
		btn_photo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
				startActivityForResult(intent2, 2);// 采用ForResult打开
				popchoose.dismiss();
			}
		});
		btn_cancle.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				popchoose.dismiss();
			}
		});

	}
    //裁剪图片
    public void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}
    //设置路径
    private void setPicToView(Bitmap mBitmap) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			return;
		}
		FileOutputStream b = null;
		File file = new File(path);
		file.mkdirs();// 创建文件夹
		String fileName = path + username+"head.jpg";// 图片名字
		try {
			b = new FileOutputStream(fileName);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			Editor editor = image.edit();
			editor.putString(username, fileName);
			editor.commit();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}
